package com.sgj.sync;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁
 * @Author: Guoji Shen
 * @Date: 2021/8/5 14:52
 */
public class SyncLockDemo {

    public static void main(String[] args) {
        // synchronized
        Object o = new Object();

        Lock lock = new ReentrantLock();

        // synchronized
        new Thread(() -> {
            synchronized (o) {
                System.out.println(Thread.currentThread().getName() + " 外层");

                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + " 中层");

                    synchronized (o) {
                        System.out.println(Thread.currentThread().getName() + " 内层");
                    }
                }
            }
        }, "t1").start();

        // lock
        new Thread(() -> {
            try{
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " 外层");

                try{
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + " 中层");

                    try{
                        lock.lock();
                        System.out.println(Thread.currentThread().getName() + " 内层");
                    } finally {
                        lock.unlock();
                    }
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}